/*
 * @Author: lizhil
 * @Date: 2021-11-22 14:15:29
 * @Last Modified by: lizhil
 * @Last Modified time: 2022-11-14 19:30:14
 */
/**
 * Api请求拦截器(错误、异常)
 */
module.exports = async (ctx, next) => {
  const getBody = (body) => {
    // 从ctx.state获取body信息
    ;['code', 'message', 'data'].forEach((key) => {
      if (ctx.state[key] != undefined) body[key] = ctx.state[key]
    })

    ctx.body = ctx.body ? ctx.body : body
  }

  // 正常
  const onSuccess = () => {
    getBody({
      code: 0,
      message: 'success',
    })
  }

  // 警告(主动)
  const onWarn = () => {
    getBody({
      code: 1,
      message: ctx.warn,
    })

    console.warn('[Middleware Api] 警告', ctx.body.message)
  }

  // 出错(异常)
  const onError = (e) => {
    console.error('[Middleware Api] 异常', e)

    getBody({
      code: 1,
      message: e && e.message ? e.message : e.toString(),
    })
  }

  try {
    await next()

    if (ctx.warn || ctx.state.code) {
      onWarn()
    } else {
      onSuccess()
    }
  } catch (e) {
    onError(e)
  }
}
